package com.jhd.fuzhou.view.login;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.LoginService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.TimeCount;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SysUserVo;

import net.zigin.commons.util.ParamsMapUtil;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class ForgetPasswordActivity extends BaseActivity {
    @BindView(R.id.btn_finish)
    Button btn_finish;
    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.et_pic_yzm)
    EditText et_pic_yzm;
    @BindView(R.id.et_yzm)
    EditText et_yzm;
    @BindView(R.id.et_new_password)
    EditText et_new_password;
    @BindView(R.id.et_confirm_password)
    EditText et_confirm_password;
    @BindView(R.id.iv_pic_yzm)
    ImageView iv_pic_yzm;
    @BindView(R.id.tv_yzm)
    TextView tv_yzm;
    private Context context = this;
    private String uuid, base64Str;
    private TimeCount timeCount;
    private boolean isGetIphoneCode = false;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_forget_password);
    }

    @Override
    protected void processLogic() {
        /*onBack();*/
        getPicCode();
        timeCount = new TimeCount(60000, 1000, tv_yzm);
    }

    @OnClick({R.id.btn_finish, R.id.iv_pic_yzm, R.id.tv_yzm})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_finish:
                //先判断手机号是否正确,首位是"1",其他10位0-9
                String mobile=et_username.getText().toString().trim();
                if(!mobile.startsWith("1")||mobile.length()!=11){
                    UtilHelper.alertMsg(context, "错误", "手机号不正确!");
                }else{
                    String verify_code=et_yzm.getText().toString().trim();
                    if(!verify_code.equals("")){
                        validCode();
                    }else{
                        UtilHelper.alertMsg(context,"错误","手机验证码不能为空");
                    }
                }
                break;
            case R.id.iv_pic_yzm://获取图片验证码
                getPicCode();
                break;
            case R.id.tv_yzm:
                checkNumberCode();
                break;
        }
    }

    private void checkNumberCode() {
        //先判断手机号是否正确,首位是"1",其他10位0-9
        String number = et_username.getText().toString().trim();
        if (!number.startsWith("1") || number.length() != 11) {
            UtilHelper.alertMsg(context, "错误", "手机号不正确!");
        } else {
            //再判断验证码是否正确
            verificationCode();
        }
    }
    private void getSysUserList() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("mobileNo", et_username.getText().toString().trim()).addParam("status", "1");
        Call<JsonForResult> jsonForResultCall = vs.getSysUserList(params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            List<SysUserVo> sysUserVo=JSON.parseArray(jsonForResult.getData().toString(), SysUserVo.class);
                            saveRegisterInfo(sysUserVo.get(0));
                        }else{
                            CustomToast.showText(context,"用户不存在!",3000,0,0).show();
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                UtilHelper.alertMsg(context, "错误", t.getMessage());
            }
        });
    }

    private void saveRegisterInfo(SysUserVo sysUserVo) {
        //最总保存前，对密码进行判断
        String password=et_confirm_password.getText().toString().trim();
        if( password.length() < 8 ||password.length()> 24){
            CustomToast.showText(context,"密码长度不能小于8位或大于24位!",3000,0,0).show();
        }else{ //数字
            String REG_NUMBER = ".*\\d+.*";
            //小写字母
            String REG_UPPERCASE = ".*[A-Z]+.*";
            //大写字母
            String REG_LOWERCASE = ".*[a-z]+.*";
            //特殊符号
            String REG_SYMBOL = ".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*";
            if( !password.matches(REG_NUMBER)||!password.matches(REG_UPPERCASE)||!password.matches(REG_LOWERCASE)||!password.matches(REG_SYMBOL)){
                CustomToast.showText(context,"密码至少包含大小写英文、数字、特殊字符!",3000,0,0).show();
            }else{
                Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
                LoginService vs = retrofit.create(LoginService.class);
                Map<String, Object> params = new LinkedHashMap<String, Object>();
                params.put("mobileNo",et_username.getText().toString().trim());
                params.put("password",et_confirm_password.getText().toString().trim());
                params.put("id",sysUserVo.getId());
                params.put("username",sysUserVo.getUserName());
                params.put("needLoginAgain",1);//是否需要重新登录 0 不需要  1 需要
                params.put("",et_confirm_password.getText().toString().trim());
                Call<JsonForResult> jsonForResultCall = vs.saveRegisterInfo(JSON.toJSON(params));
                jsonForResultCall.enqueue(new Callback<JsonForResult>() {
                    @Override
                    public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                        try {
                            JsonForResult jsonForResult = response.body();
                            if (jsonForResult != null && jsonForResult.isSuccess()) {
                                CustomToast.showText(context,"密码修改成功",3000,0,0).show();
                                finish();
                            } else {
                                UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                            }
                        } catch (Exception e) {
                            UtilHelper.alertMsg(context, "错误", e.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(Call<JsonForResult> call, Throwable t) {
                        UtilHelper.alertMsg(context, "错误", t.getMessage());
                    }
                });
            }
        }
    }
    //验证图片验证码
    private void verificationCode() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("code", et_pic_yzm.getText().toString().trim()).addParam("uuid", uuid);
        Call<JsonForResult> jsonForResultCall = vs.verificationCode(params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        handler.sendEmptyMessage(0);//0是判断验证码正确,可以直接调用去获取手机验证码
                    } else {
                        getPicCode();//验证码错误,重新获取
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                UtilHelper.alertMsg(context, "错误", t.getMessage());
            }
        });
    }
    /*检查短信验证码*/
    private void validCode() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("mobileNo", et_username.getText().toString().trim()).addParam("validCode", et_yzm.getText().toString().trim());
        Call<JsonForResult> jsonForResultCall = vs.validCode(params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        getSysUserList();
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                UtilHelper.alertMsg(context, "错误", t.getMessage());
            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0://获取手机验证码,验证码不可编辑
                    et_pic_yzm.setFocusable(false);
                    getIphoneCode();
                    break;
                case 1://获取手机验证码成功,将按钮设置成不可点击
                    isGetIphoneCode = true;
                    timeCount.start();
                    break;
            }

        }
    };

    private void getIphoneCode() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("mobileNo", et_username.getText().toString().trim()).addParam("type", "validate")/*.addParam("sysUserId",application.getSysUserId())*/;
        Call<JsonForResult> jsonForResultCall = vs.sendValidCode(params);
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        handler.sendEmptyMessage(1);//1是判断验证码发送成功
                    } else {
                        getPicCode();//验证码错误,重新获取
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                UtilHelper.alertMsg(context, "错误", t.getMessage());
            }
        });
    }

    private void getPicCode() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        LoginService vs = retrofit.create(LoginService.class);
        Call<JsonForResult> jsonForResultCall = vs.getImage();//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        uuid = JSON.parseObject(jsonForResult.getData().toString()).getString("uuid");
                        base64Str = JSON.parseObject(jsonForResult.getData().toString()).getString("base64Str");
                        byte[] decode = Base64.decode(base64Str.split(",")[1], Base64.DEFAULT);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(decode, 0, decode.length);
                        iv_pic_yzm.setImageBitmap(bitmap);
                        et_pic_yzm.setFocusable(true);
                        et_pic_yzm.setFocusableInTouchMode(true);
                        et_pic_yzm.requestFocus();
                    } else {
                        UtilHelper.alertMsg(context, "错误", "获取图片验证码失败");
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "获取图片验证码失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
}